﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using Portal.Systems.Model;
using Portal.Database.Service;
using Portal.Web.Utility;
using Portal.Core;
using Portal.Systems.Bussiness.Template;
using Portal.Utility;
using System.Collections.ObjectModel;

namespace Portal.Systems.Bussiness
{
    public class GroupRoleProcessBll
    {
        public static GroupRoleCls[] ReadingGroupRoles(string SiteId,string Keyword)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string AssetCode = WebSessionUtility.GetCurrentLoginUser().AssetCode;
            string DataLanguage = WebConfig.GetDataLanguage(OSiteParam);
            string Query =
                "select TableGroupRole.* from TableGroupRole " +
                   "     where AssetCode=@AssetCode order by SortIndex";
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("AssetCode", AssetCode),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new GroupRoleCls[0];
            }
            GroupRoleCls[] CmsAccount = GroupRoleParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return CmsAccount;
        }


        public static RoleCls[] ReadingRoleForGroupRole(string SiteId, string GroupRoleId)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string AssetCode = WebSessionUtility.GetCurrentLoginUser().AssetCode;
            string DataLanguage = WebConfig.GetDataLanguage(OSiteParam);
            string Query =
                " select TableRole.* from TableRoleInGroupRole " +
                "       join TableRole on TableRole.RoleId=frkRoleId" +
                " where AssetCode=@AssetCode and frkGroupRoleId=@GroupRoleId order by RoleCode";
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("GroupRoleId", GroupRoleId),
                        new DbParam("AssetCode", AssetCode),
                    });

            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new RoleCls[0];
            }
            RoleCls[] Roles = RoleParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return Roles;
        }



        public static RoleCls[] ReadingRoleBelongGroupRole(string SiteId, string GroupRoleId, string Keyword)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string AssetCode = WebSessionUtility.GetCurrentLoginUser().AssetCode;
            string DataLanguage = WebConfig.GetDataLanguage(OSiteParam);
            string Query =
                " select TableRole.* from TableRoleInGroupRole " +
                "       join TableRole on TableRole.RoleId=frkRoleId" +
                " where AssetCode=@AssetCode and frkGroupRoleId=@GroupRoleId ";
            if (!string.IsNullOrEmpty(Keyword))
            {
                Keyword = FunctionUtilities.CorrectForSearch(Keyword);
                Query += " and RoleName like N'%" + Keyword + "%'";
            }
            Query+=" order by RoleCode";
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("GroupRoleId", GroupRoleId),
                        new DbParam("AssetCode", AssetCode),
                    });

            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new RoleCls[0];
            }
            RoleCls[] Roles = RoleParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return Roles;
        }


        public static RoleCls[] ReadingRoleAvailableForGroupRole(string SiteId, string GroupRoleId, string Keyword)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string AssetCode = WebSessionUtility.GetCurrentLoginUser().AssetCode;
            string DataLanguage = WebConfig.GetDataLanguage(OSiteParam);
            string Query =
                " select * from TableRole " +
                "   where AssetCode=@AssetCode and RoleId not in " +
                "       (" +
                "           select frkRoleId from TableRoleInGroupRole" +
                "               where frkGroupRoleId=@GroupRoleId " +
                "       ) ";
            if (!string.IsNullOrEmpty(Keyword))
            {
                Keyword = FunctionUtilities.CorrectForSearch(Keyword);
                Query += " and RoleName like N'%" + Keyword + "%'";
            }
            DataSet dsResult =
                    DBService.GetDataSet(null, Query,
                    new DbParam[] 
                    { 
                        new DbParam("GroupRoleId", GroupRoleId),
                        new DbParam("AssetCode", AssetCode),
                    });

            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return new RoleCls[0];
            }
            RoleCls[] Roles = RoleParser.ParseFromDataTable(dsResult.Tables[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return Roles;
        }

        public static GroupRoleCls CreateGroupRoleModel(string SiteId, string GroupRoleId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DataSet dsResult =
                    DBService.GetDataSet(null, "select * from TableGroupRole " +
                                               "     where GroupRoleId=@GroupRoleId",
                    new DbParam[] 
                    { 
                        new DbParam("GroupRoleId", GroupRoleId),
                    });
            if (dsResult.Tables[0].Rows.Count == 0)
            {
                return null;
            }
            GroupRoleCls OGroupRole = GroupRoleParser.ParseFromDataRow(dsResult.Tables[0].Rows[0]);
            dsResult.Clear();
            dsResult.Dispose();
            return OGroupRole;
        }


        public static string AddGroupRole(
            IDbTransaction Trans,
            string SiteId, 
            string AssetCode,
            string GroupRoleId,
            string GroupRoleName, 
            int    SortIndex)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            if (string.IsNullOrEmpty(GroupRoleId))
            {
                GroupRoleId = System.Guid.NewGuid().ToString();
            }
            string DataLanguage = WebConfig.GetDataLanguage(OSiteParam);
            DBService.Insert(Trans, "TableGroupRole",
                    new DbParam[] 
                    { 
                        new DbParam("GroupRoleId", GroupRoleId),
                        new DbParam("GroupRoleName", GroupRoleName),
                        new DbParam("AssetCode", AssetCode),
                        new DbParam("DataLanguage", DataLanguage),
                        new DbParam("SortIndex", SortIndex),
                    });
            return GroupRoleId;
        }


        public static void SaveGroupRole(
            IDbTransaction Trans,
            string SiteId, 
            string GroupRoleId, 
            string GroupRoleName,
            int SortIndex)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DBService.Update(Trans, "TableGroupRole", "GroupRoleId", GroupRoleId,
                    new DbParam[] 
                    { 
                        new DbParam("GroupRoleName", GroupRoleName),
                        new DbParam("SortIndex", SortIndex),
                    });
        }


        public static void DeleteGroupRole(IDbTransaction Trans, string SiteId, string GroupRoleId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query =
                " Delete from TableRoleInGroupRole  where frkGroupRoleId=@GroupRoleId; "+
                " Delete from TableGroupRole where GroupRoleId=@GroupRoleId; ";
            DBService.ExecuteNonQuery(Trans, Query,
                    new DbParam[] 
                    { 
                        new DbParam("GroupRoleId", GroupRoleId),
                    });
        }

        public static void AddRoleToGroupRole(IDbTransaction Trans, string SiteId, string GroupRoleId, string RoleId)
        {
            string RoleInGroupRoleId = System.Guid.NewGuid().ToString();
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            DBService.Insert(Trans, "TableRoleInGroupRole",
                    new DbParam[] 
                    { 
                        new DbParam("RoleInGroupRoleId", RoleInGroupRoleId),
                        new DbParam("frkGroupRoleId", GroupRoleId),
                        new DbParam("frkRoleId", RoleId),
                    });
        }

        public static void RemoveRoleFromGroupRole(IDbTransaction Trans, string SiteId, string RoleInGroupRoleId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query = "Delete from TableRoleInGroupRole where RoleInGroupRoleId=@RoleInGroupRoleId";
            DBService.ExecuteNonQuery(Trans, Query,
                    new DbParam[] 
                    { 
                        new DbParam("RoleInGroupRoleId", RoleInGroupRoleId),
                    });
        }

        public static void RemoveRoleFromGroupRole(IDbTransaction Trans, string SiteId, string GroupRoleId,string RoleId)
        {
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            string Query = "Delete from TableRoleInGroupRole where frkGroupRoleId=@GroupRoleId and frkRoleId=@RoleId";
            DBService.ExecuteNonQuery(Trans, Query,
                    new DbParam[] 
                    { 
                        new DbParam("GroupRoleId", GroupRoleId),
                        new DbParam("RoleId", RoleId),
                    });
        }

        public static Collection<UserCls> ReadingUsersInGroupRoles(string SiteId, string[] GroupRoleIds)
        {
            Collection<UserCls> 
                ColUsers = new Collection<UserCls> { };
            IDatabaseService DBService = WebDatabaseService.CreateDBService(SiteId);
            for (int iIndexGroupRole = 0; iIndexGroupRole < GroupRoleIds.Length; iIndexGroupRole++)
            {
                string Query = " select RoleId,RoleName from TableRoleInGroupRole "+
                               "        join TableRole on TableRole.RoleId=frkRoleId"+
                               "     where frkGroupRoleId=@GroupRoleId";
                DataTable dtRole=DBService.GetDataTable(null, Query,
                   new DbParam[] 
                    { 
                        new DbParam("GroupRoleId", GroupRoleIds[iIndexGroupRole]),
                    });

                for (int iIndexRole = 0; iIndexRole < dtRole.Rows.Count; iIndexRole++)
                {
                    string RoleId = (string)dtRole.Rows[iIndexRole]["RoleId"];
                    string RoleName = (string)dtRole.Rows[iIndexRole]["RoleName"];
                    //doan nay lay user

                    Query = " select TableUser.* from TableUserRole "+
                            "       join TableUser on TableUser.UserId=frkUserId"+
                            "    where frkRoleId=@RoleId";
                    DataTable dtUser= DBService.GetDataTable(null, Query,
                       new DbParam[] 
                    { 
                        new DbParam("RoleId", RoleId),
                    });
                    UserCls[] Users = UserParser.ParseFromDataTable(dtUser);
                    for (int iIndexUser = 0; iIndexUser < dtUser.Rows.Count; iIndexUser++)
                    {
                        Users[iIndexUser].RoleId = RoleId;
                        Users[iIndexUser].RoleName = RoleName;

                        ColUsers.Add(Users[iIndexUser]);
                    }
                }
            }
            return ColUsers;
        }

        public static string[] ConvertSystemGroupRoleFromWorkflowGroupRole(
            string SiteId, 
            string WorkflowDefId,
            string[] WorkflowGroupRoleIds)
        {
            WorkflowDefMapRoleCls[] WorkflowDefMapRoles = WorkflowDefProcessBll.ReadingWorkflowDefMapRoles(SiteId, WorkflowDefId);
            string[] GroupRoleIds = new string[WorkflowGroupRoleIds.Length];
            for (int iIndex = 0; iIndex < WorkflowGroupRoleIds.Length; iIndex++)
            {
                for (int iCheck = 0; iCheck < WorkflowDefMapRoles.Length; iCheck++)
                {
                    if (string.IsNullOrEmpty(WorkflowDefMapRoles[iCheck].MapGroupRoleId))
                    {
                        throw new Exception("Chưa thiếp lập bảng map quy trình!");
                    }
                    if (WorkflowGroupRoleIds[iIndex].Equals(WorkflowDefMapRoles[iCheck].WorkflowRoleId))
                    {
                        GroupRoleIds[iIndex] = WorkflowDefMapRoles[iCheck].MapGroupRoleId;
                        break;
                    }
                }
            }
            return GroupRoleIds;
        }
    }
}

